package ConcurrentHashMap_10;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
public class 基础用法_多线程安全写入和读取 {
    public static void main(String[] args) {
        final ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
        final int THREAD_COUNT = 200;
        // 写入线程
        for (int i = 0; i < THREAD_COUNT; i++) {
            final int key = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep((long)(Math.random() * 100)); // 模拟处理时间
                        map.put(key, "Value-" + key);
                        System.out.println(Thread.currentThread().getName() + " 写入键: " + key);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "写入线程-" + i).start();
        }

        // 读取线程
        for (int i = 0; i < THREAD_COUNT; i++) {
            final int key = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(150); // 稍后开始读取
                        String value = map.get(key);
                        System.out.println(Thread.currentThread().getName() + " 读取键: " + key + " -> " + value);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "读取线程-" + i).start();
        }

        // 等待所有操作完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终Map大小: " + map.size());
    }
}